'''
Created on 2011-5-19

@author: lchengh2
'''
import os
import zipfile
import urllib
import shutil

from deploymentsetting import DeploymentSetting

from myhomework.account.daos import *
from myhomework.homework.daos import *

class FileManager(object):
    
    settings = None
    root_path = ''
    src_path = ''
    teamwork_folder_path = ''
    personal_homework_folder_path = ''
    teamwork_src_path = ''
    personal_homework_src_path = ''
    
    _last_src_file = ''
    
    def __init__(self,the_settings):
        pass
    
    @staticmethod        
    def initilize():
        FileManager.settings = DeploymentSetting.load_setting()
        
        if(FileManager.settings == None):
            raise FileManagerInitializeError('loading settings errors!')
        
        FileManager.root_path = FileManager.settings.get_root_path()
        FileManager.src_path = FileManager.settings.get_src_path()
        FileManager.teamwork_folder_path = FileManager.root_path + '/teamwork'
        FileManager.personal_homework_folder_path = FileManager.root_path + '/personal_homework'
        FileManager.teamwork_src_path = FileManager.src_path + '/teamwork'
        FileManager.personal_homework_src_path = FileManager.src_path + '/personal_homework'
        
        if(FileManager.does_folder_exist(FileManager.root_path) == False):
            os.mkdir(FileManager.root_path)
            
        if(FileManager.does_folder_exist(FileManager.src_path) == False):
            os.mkdir(FileManager.src_path)        
                        
        if(FileManager.does_folder_exist(FileManager.teamwork_folder_path) == False):
            os.mkdir(FileManager.teamwork_folder_path)
            
        if(FileManager.does_folder_exist(FileManager.teamwork_src_path) == False):
            os.mkdir(FileManager.teamwork_src_path)
             
        if(FileManager.does_folder_exist(FileManager.personal_homework_folder_path) == False):
            os.mkdir(FileManager.personal_homework_folder_path)
            
        if(FileManager.does_folder_exist(FileManager.personal_homework_src_path) == False):
            os.mkdir(FileManager.personal_homework_src_path)
    
    @staticmethod
    def delete_homework_folder(the_homework):
        
        homework_folder_path = FileManager.get_homework_path(the_homework)
        
        if(FileManager.does_folder_exist(homework_folder_path) == True):
            shutil.rmtree(homework_folder_path)
        else:
            raise FolderDoesNotExist(homework_folder_path)   

    @staticmethod       
    def delete_homework_source_folder(the_homework):
        
        homework_source_folder_path = FileManager.get_homework_source_path(the_homework)
        
        if(FileManager.does_folder_exist(homework_source_folder_path) == True):
            shutil.rmtree(homework_source_folder_path)
        else:
            raise FolderDoesNotExist(homework_source_folder_path)               

    @staticmethod            
    def delete_homework_sumitted_folder(the_homework,
                                        the_submitter):
        ths_hs_path = FileManager.get_homework_submitted_path(the_homework, 
                                                              the_submitter)
        
        if(FileManager.does_folder_exist(ths_hs_path) == True):
            shutil.rmtree(ths_hs_path)
        else:
            raise FolderDoesNotExist(ths_hs_path)
    
    @staticmethod
    def delete_homework_submitted_source_path(the_homework,
                                              the_submitter):
        the_hs_src_folder_path = FileManager.get_homework_submitted_source_path(the_homework, 
                                                                              the_submitter)
        if(FileManager.does_folder_exist(the_hs_src_folder_path) == True):
            shutil.rmtree(the_hs_src_folder_path)

    @staticmethod        
    def extract_and_save_zip_file(the_homework,
                                  the_submitter):
        the_zip_file = FileManager.get_homework_submitted_source_file(the_homework, 
                                                                       the_submitter)
             
        the_hs_path = FileManager.get_homework_submitted_path(the_homework, 
                                                              the_submitter)
                
        def dir_create(dir):
            if not os.path.exists(dir):
                os.mkdir(dir)
        
        z = zipfile.ZipFile(the_zip_file, 'r')
        for f in z.namelist():
            path = os.path.join(the_hs_path, unicode(f,'gb2312'))
            if path.endswith("/"):
                dir_create(path)
            else:
                file(path, 'wb').write(z.read(f))
        
    '''
    return the path of a folder of the_homework which is submitted by the_submitter
    '''
    @staticmethod
    def get_homework_submitted_path(the_homework,
                                    the_submitter):
        homework_folder_path = FileManager.get_homework_path(the_homework)

        hs_name = ''
        if(the_homework.type == 'personal'):
            hs_name = str(the_submitter.student_id)
                
        if(the_homework.type == 'team'):
            the_group = the_submitter.group
            if(the_group <> None):
                hs_name = str(the_group.id)
            else:
                raise GroupIsNoneError('')
        return homework_folder_path + '/' + hs_name

    '''
    return the path of a folder of the_homework, which is used for storing homework information submitted by students
    '''
    @staticmethod
    def get_homework_path(the_homework):
        homework_id = the_homework.id

        if(the_homework.type == 'team'):
            homework_folder_path = FileManager.teamwork_folder_path + '/' + str(homework_id)
        if(the_homework.type == 'personal'):
            homework_folder_path = FileManager.personal_homework_folder_path + '/' + str(homework_id)
            
        return homework_folder_path
    
    
    '''
    return the path of the_homework ,which is used for storing source files about the_homework
    '''
    @staticmethod
    def get_homework_source_path(the_homework):
        homework_id = the_homework.id

        if(the_homework.type == 'team'):
            homework_source_path = FileManager.teamwork_src_path + '/' + str(homework_id)
        if(the_homework.type == 'personal'):
            homework_source_path = FileManager.personal_homework_src_path + '/' + str(homework_id)
            
        return homework_source_path

    @staticmethod
    def get_homework_submitted_source_path(the_homework,
                                          the_submitter):
        
        the_homework_source_path = FileManager.get_homework_source_path(the_homework)

        src_folder_name = ''
        if(the_homework.type == 'personal'):
            src_folder_name = str(the_submitter.student_id)
                
        if(the_homework.type == 'team'):
            the_group = the_submitter.group
            if(the_group <> None):
                src_folder_name = str(the_group.id)
            else:
                raise GroupIsNoneError('')
            
        return the_homework_source_path + '/' + src_folder_name

    @staticmethod
    def get_homework_submitted_picture(the_homework,
                                       the_submitter):
        the_hs_path = FileManager.get_homework_submitted_path(the_homework, 
                                                              the_submitter)
            
        return the_hs_path + '/' + 'pic.png'
    
    @staticmethod
    def create_homework_submitted_source_file(the_homework,
                                           the_submitter):  
        the_source_path = FileManager.get_homework_submitted_source_path(the_homework,
                                                                        the_submitter)
        result = ''
        src_name = ''
        if(the_homework.type == 'personal'):
            src_name = str(the_submitter.student_id)
                
        if(the_homework.type == 'team'):
            the_group = the_submitter.group
            if(the_group <> None):
                src_name = str(the_group.id)
            else:
                raise GroupIsNoneError('')
            
        result = the_source_path + '/' + src_name
        
        num = 0
        temp = result + '.zip'
        while(FileManager.does_folder_exist(temp) == True):
            num += 1
            temp = result + '(' + str(num) + ')' + '.zip'
        
        return temp
    
    @staticmethod
    def get_homework_submitted_source_file(the_homework,
                                           the_submitter):  
        the_source_path = FileManager.get_homework_submitted_source_path(the_homework,
                                                                        the_submitter)
        src_name = ''
        if(the_homework.type == 'personal'):
            src_name = str(the_submitter.student_id)
                
        if(the_homework.type == 'team'):
            the_group = the_submitter.group
            if(the_group <> None):
                src_name = str(the_group.id)
            else:
                raise GroupIsNoneError('')
            
        all_src_name = the_source_path + '/' + src_name
        
        num = 0
        temp = all_src_name + '.zip'
        result = ''
        while(FileManager.does_folder_exist(temp) == True):
            result = temp
            num += 1
            temp = all_src_name + '(' + str(num) + ')' + '.zip'
        
        if(result == ''):
            raise ZipFileDoesNotExist(src_name)
        
        return result
    
    @staticmethod
    def does_folder_exist(folder_path):
        return os.path.exists(folder_path)
     
    @staticmethod
    def get_ready_for_saving_homework(the_homework_id,
                                     the_submitter_student_id):

        the_homework = HomeworkDao.get_homework_by_id(the_homework_id)
        the_submitter = UserDao.get_user_by_student_id(the_submitter_student_id)

        #create homework folder
        print 'ok1!!!!!!!!!'
        homework_folder_path = FileManager.get_homework_path(the_homework)
        print 'ok2!!!!!!!!!'
        if(FileManager.does_folder_exist(homework_folder_path) == False):
            os.mkdir(homework_folder_path)           
            
        #create homework folder of source
        homework_source_path = FileManager.get_homework_source_path(the_homework)
        if(FileManager.does_folder_exist(homework_source_path) == False):
            os.mkdir(homework_source_path)

        #create homework_submitted folder of source
        the_hs_src_path = FileManager.get_homework_submitted_source_path(the_homework, 
                                                                         the_submitter)
        if(FileManager.does_folder_exist(the_hs_src_path) == False):
            os.mkdir(the_hs_src_path)

        #create homework_submitted_info folder
        the_hs_path = FileManager.get_homework_submitted_path(the_homework, 
                                                      the_submitter)
        if(FileManager.does_folder_exist(the_hs_path) == False):
            os.mkdir(the_hs_path)
        else:
            shutil.rmtree(the_hs_path)
            os.mkdir(the_hs_path)
            
        FileManager._last_src_file = FileManager.create_homework_submitted_source_file(the_homework, 
                                                                                       the_submitter)
        pic_path = FileManager.get_homework_submitted_picture(the_homework, the_submitter)
        
        result = []
        result.append(FileManager._last_src_file)
        result.append(pic_path)
        return result
    
    @staticmethod
    def save_homework_submitted(the_homework_id,
                                the_submitter_student_id,
                                the_contribution_list = None):
        the_homework = HomeworkDao.get_homework_by_id(the_homework_id)
        the_submitter = UserDao.get_user_by_student_id(the_submitter_student_id)
        
        the_hs_path = FileManager.get_homework_submitted_path(the_homework, 
                                                              the_submitter)   
        the_src_file = FileManager.get_homework_submitted_source_file(the_homework, 
                                                                      the_submitter)
        the_pic_path = FileManager.get_homework_submitted_picture(the_homework, 
                                                                  the_submitter)
        if(FileManager.does_folder_exist(the_hs_path) == False):
            raise FolderDoesNotExist(the_hs_path)
        
        if(FileManager.does_folder_exist(the_src_file) == False):
            raise ZipFileDoesNotExist(the_src_file)
        
        hs = HomeworkSubmitedInfo(homework = the_homework,
                                  src = the_src_file,
                                  url = the_hs_path,
                                  pic = the_pic_path,
                                  score = 0,
                                  rank = 0)
        HomeworkSubmitedDao.add_homework_submited(hs, the_submitter, 
                                                  the_contribution_list)
        FileManager.extract_and_save_zip_file(the_homework,
                                              the_submitter)
        FileManager._last_src_file = ''
    
    @staticmethod
    def remove_homework_submitted(the_homework,
                                  the_submitter):
        
        HomeworkSubmitedDao.delete_homework_submited(the_homework,
                                                     the_submitter)
        
        FileManager.delete_homework_sumitted_folder(the_homework, 
                                                    the_submitter)
              
        FileManager.delete_homework_submitted_source_path(the_homework, 
                                                          the_submitter)
        

FileManager.initilize()
    